package com.filldream.fastboot.core.event.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.filldream.fastboot.base.entity.AppOpenUnionBind;
import com.filldream.fastboot.base.mapper.AppOpenUnionBindMapper;
import com.filldream.fastboot.common.util.entity.wx.WxUser;
import com.filldream.fastboot.common.util.DDErrorUtil;
import com.filldream.fastboot.common.util.JsonUtil;
import com.filldream.fastboot.core.event.WxAppOpenUnionIdEvent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;


/**
 * 事件监听，处理逻辑的地方
 */
@AllArgsConstructor
@Slf4j
@Component
public class WxAppOpenUnionIdEventListener implements ApplicationListener<WxAppOpenUnionIdEvent> {

	private AppOpenUnionBindMapper appOpenUnionBindMapper;

	@Async
	public void onApplicationEvent(WxAppOpenUnionIdEvent testEvent) {
		WxUser wxUser = (WxUser)testEvent.getSource();
		String appId = wxUser.getAppId();
		String openId = wxUser.getOpenid();
		String unionId = wxUser.getUnionid();

		if( StringUtils.isBlank(appId) || StringUtils.isBlank(openId) ){
			log.error("微信记录参数不能为空.." + JsonUtil.toJson(wxUser));
			DDErrorUtil.directSend("微信记录参数不能为空.." + JsonUtil.toJson(wxUser));
			return;
		}

		AppOpenUnionBind sql = new AppOpenUnionBind();
		sql.setAppId(appId);

		if(StringUtils.isNotBlank(openId)){
			sql.setOpenId(openId);
		}

		if(StringUtils.isNotBlank(unionId)){
			sql.setUnionId(unionId);
		}
//		AppOpenUnionBind appOpenUnionBind = appOpenUnionBindMapper.selectOne(new AppOpenUnionBind().setAppId(wxUser.getAppId()).setOpenId(openId));
		AppOpenUnionBind appOpenUnionBind = appOpenUnionBindMapper.selectOne(
				new LambdaQueryWrapper<AppOpenUnionBind>().eq(AppOpenUnionBind::getAppId,wxUser.getAppId())
						.eq(AppOpenUnionBind::getOpenId,openId)
		);
		if( appOpenUnionBind == null ){
			appOpenUnionBindMapper.insert(sql);
		}else{
			if( StringUtils.isBlank(appOpenUnionBind.getOpenId()) && StringUtils.isNotBlank(openId) ){
				appOpenUnionBind.setOpenId(openId);
			}

			if( StringUtils.isBlank(appOpenUnionBind.getUnionId()) && StringUtils.isNotBlank(unionId) ){
				appOpenUnionBind.setUnionId(unionId);
			}
			appOpenUnionBindMapper.updateById(appOpenUnionBind);
		}
		return;
	}
}